package com.jingxuan.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jingxuan.common.exception.BusinessException;
import com.jingxuan.common.result.ResultCode;
import com.jingxuan.dto.request.AddCartItemRequest;
import com.jingxuan.dto.response.AddCartItemResponse;
import com.jingxuan.dto.response.ClearCartResponse;
import com.jingxuan.dto.response.GetCartItemResponse;
import com.jingxuan.dto.response.SetCartItemSelectedResponse;
import com.jingxuan.dto.response.UpdateCartItemQuantityResponse;
import com.jingxuan.entity.Cart;
import com.jingxuan.entity.Product;
import com.jingxuan.mapper.CartMapper;
import com.jingxuan.mapper.ProductsMapper;
import com.jingxuan.service.CartService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class CartServiceImpl implements CartService {
    /** 默认商品数量 */
    private static final int DEFAULT_QUANTITY = 1;

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductsMapper productsMapper;

    /**
     * 添加商品到购物车
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AddCartItemResponse addCartItem(Long userId, AddCartItemRequest request) {
        if (request == null || request.getProductId() == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR, "商品id不能为空");
        }

        Product product = productsMapper.selectById(request.getProductId());
        if (product == null) {
            throw new BusinessException(ResultCode.PRODUCT_NOT_FOUND);
        }

        int quantityToAdd = resolveQuantity(request.getQuantity());
        /** 查询购物车商品 */
        Cart existingItem = cartMapper.selectByUserIdAndProductId(userId, request.getProductId());
        int finalQuantity;
        if (existingItem == null) {
            Cart cart = new Cart();
            cart.setUserId(userId);
            cart.setProductId(request.getProductId());
            cart.setQuantity(quantityToAdd);
            cart.setSelected(Boolean.TRUE);
            int inserted = cartMapper.insertCartItem(cart);
            if (inserted <= 0) {
                throw new BusinessException(ResultCode.DATABASE_ERROR, "添加购物车失败");
            }
            finalQuantity = cart.getQuantity();
        } else {
            finalQuantity = existingItem.getQuantity() + quantityToAdd;
            int updated = cartMapper.updateQuantity(userId, request.getProductId(), finalQuantity);
            if (updated <= 0) {
                throw new BusinessException(ResultCode.DATABASE_ERROR, "更新购物车失败");
            }
        }

        AddCartItemResponse response = new AddCartItemResponse();
        response.setProductId(request.getProductId());
        response.setQuantity(finalQuantity);
        response.setUpdatedAt(LocalDateTime.now());

        log.info("添加商品到购物车成功，商品id：{}，用户id：{}，商品数量：{}", request.getProductId(), userId, finalQuantity);
        return response;
    }

    @Override
    public GetCartItemResponse getCartItems(Long userId) {
        List<Cart> cartItems = cartMapper.selectByUserId(userId);
        /** 查询购物车商品列表 */
        GetCartItemResponse response = new GetCartItemResponse();
        GetCartItemResponse.Summary summary = new GetCartItemResponse.Summary();
        summary.setTotalQuantity(0);
        summary.setSelectedCount(0);
        summary.setSelectedAmount(BigDecimal.ZERO);
        response.setSummary(summary);
        response.setItems(new ArrayList<>());

        if (cartItems == null || cartItems.isEmpty()) {
            return response;
        }

        List<String> productIds = cartItems.stream()
                .map(Cart::getProductId)
                .distinct()
                .collect(Collectors.toList());
        if (productIds.isEmpty()) {
            return response;
        }

        List<Product> products = productsMapper.selectByIds(productIds);
        Map<String, Product> productMap = products.stream()
                .collect(Collectors.toMap(Product::getId, product -> product));
        /** 查询商品列表 */
        List<GetCartItemResponse.Item> items = new ArrayList<>();
        int totalQuantity = 0;
        int selectedCount = 0;
        BigDecimal selectedAmount = BigDecimal.ZERO;

        for (Cart cartItem : cartItems) {
            Product product = productMap.get(cartItem.getProductId());
            if (product == null) {
                log.warn("商品{}不存在，跳过", cartItem.getProductId());
                continue;
            }

            int quantity = cartItem.getQuantity() != null ? cartItem.getQuantity() : 0;
            BigDecimal unitPrice = product.getPrice() != null ? product.getPrice() : BigDecimal.ZERO;
            BigDecimal amount = unitPrice.multiply(BigDecimal.valueOf(quantity));

            GetCartItemResponse.Item item = new GetCartItemResponse.Item();
            item.setProductId(cartItem.getProductId());
            item.setQuantity(quantity);
            item.setSelected(Boolean.TRUE.equals(cartItem.getSelected()));
            item.setUnitPrice(unitPrice);
            item.setAmount(amount);
            items.add(item);

            totalQuantity += quantity;
            if (Boolean.TRUE.equals(cartItem.getSelected())) {
                selectedCount += quantity;
                selectedAmount = selectedAmount.add(amount);
            }
        }

        summary.setTotalQuantity(totalQuantity);
        summary.setSelectedCount(selectedCount);
        summary.setSelectedAmount(selectedAmount);

        response.setItems(items);
        response.setSummary(summary);
        return response;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UpdateCartItemQuantityResponse updateCartItemQuantity(Long userId, String productId, Integer quantity) {
        if (productId == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR, "商品id不能为空");
        }
        if (quantity == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR, "商品数量不能为空");
        }

        Cart cartItem = cartMapper.selectByUserIdAndProductId(userId, productId);
        if (cartItem == null) {
            throw new BusinessException(ResultCode.NOT_FOUND, "购物车商品不存在");
        }

        int finalQuantity = quantity;
        if (quantity <= 0) {
            cartMapper.deleteByUserIdAndProductId(userId, productId);
            finalQuantity = 0;
        } else {
            int updated = cartMapper.updateQuantity(userId, productId, quantity);
            if (updated <= 0) {
                throw new BusinessException(ResultCode.DATABASE_ERROR, "更新购物车商品数量失败");
            }
        }

        UpdateCartItemQuantityResponse response = new UpdateCartItemQuantityResponse();
        response.setProductId(productId);
        response.setQuantity(finalQuantity);

        log.info("更新购物车商品数量成功，用户id：{}，商品id：{}，商品数量：{}", userId, productId, finalQuantity);
        return response;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SetCartItemSelectedResponse setCartItemSelected(Long userId, String productId, Boolean selected) {
        if (productId == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR, "商品id不能为空");
        }
        if (selected == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR, "是否选中不能为空");
        }

        Cart cartItem = cartMapper.selectByUserIdAndProductId(userId, productId);
        if (cartItem == null) {
            throw new BusinessException(ResultCode.NOT_FOUND, "购物车商品不存在");
        }

        int updated = cartMapper.updateSelected(userId, productId, selected);
        if (updated <= 0) {
            throw new BusinessException(ResultCode.DATABASE_ERROR, "更新购物车商品选中状态失败");
        }

        SetCartItemSelectedResponse response = new SetCartItemSelectedResponse();
        response.setProductId(productId);
        response.setSelected(selected);
        response.setQuantity(cartItem.getQuantity());
        response.setUpdatedAt(LocalDateTime.now());

        log.info("更新购物车商品选中状态成功，用户id：{}，商品id：{}，是否选中：{}", userId, productId, selected);
        return response;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ClearCartResponse clearCart(Long userId) {
        int clearedCount = cartMapper.clearCart(userId);

        ClearCartResponse response = new ClearCartResponse();
        response.setClearedCount(clearedCount);
        response.setClearedAt(LocalDateTime.now());

        log.info("清空购物车成功，用户id：{}，清空商品数量：{}", userId, clearedCount);
        return response;
    }

    private int resolveQuantity(Integer quantity) {
        return (quantity == null || quantity <= 0) ? DEFAULT_QUANTITY : quantity;
    }
}
